<template>
  <div id="space-category-analyze">
    <a-card title="图库分类占用">
      <v-chart :option="options" style="height: 320px; max-width: 100%;" :loading="loading" />
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import {computed, ref, watchEffect} from 'vue'
import {getSpaceCategoryAnalyzeUsingPost} from '@/api/spaceAnalyzeController'
import { message } from 'ant-design-vue'
import VChart from "vue-echarts";
import "echarts";
import * as echarts from "echarts"

interface Props {
  queryAll?: boolean
  queryPublic?: boolean
  spaceId?: number
}

const props = withDefaults(defineProps<Props>(), {
  // 默认为false，这样如果单独分析某空间只需要传spaceId
  queryAll: false,
  queryPublic: false,
})

// 接受图表数据
const dataList = ref<API.SpaceCategoryAnalyzeResponse[]>([])
const loading = ref<boolean>(true) // 默认为true，加载

/**
 * 加载数据
 */
const fetchData = async () => {
  loading.value = true
  const res = await getSpaceCategoryAnalyzeUsingPost({
    queryAll: props.queryAll,
    queryPublic: props.queryPublic,
    spaceId: props.spaceId,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  // 加载完毕结束加载状态
  loading.value = false
}

/**
 * 监听变量，改变时触发数据的重新加载
 * 只要有任何一个值发生变化，都会重新执行封装的函数
 */
watchEffect(() => {
  fetchData()
})

const colorArray = (dataArray, color) => {
  if(dataArray && dataArray.length > 0) {
    return dataArray.map(item => ({
      value: item,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0.2, color: color },
          { offset: 1, color: color + '00' }
        ], false)
      }
    }))
  }
}

// 调整坐标轴刻度
const unifiedDivision = (maxNum) => {
  for (let i = 0; i < 10; i++) {
    if (maxNum % 10 !== 0) {
      maxNum++;
    } else {
      return maxNum / 5;
    }
  }
};

// 计算Y轴最大值
const calcMaxAxis = (data) => {
  let max = unifiedDivision(Math.ceil(Math.max(...data))) * 5;
  let i = 0;
  while (max > 10) {
    max = max / 10;
    i++;
  }
  return Math.pow(10, i) * Math.ceil(max);
};



// 图表内容参数
const options = computed(() => {

  const categories = dataList.value.map((item) => item.category)
  const countData = dataList.value.map((item) => item.count)
  const sizeData = dataList.value.map((item) => (item.totalSize / (1024 * 1024)).toFixed(2)) // 转为 MB
  const maxLeft = calcMaxAxis(countData);
  const maxRight = calcMaxAxis(sizeData);

  return {
    tooltip: {
      trigger: 'axis',
      textStyle: { fontSize: 14 },
      formatter: function (param) {
        let res = param[0].name + '<br>';
        param.forEach(item => {
          const marker = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${item.color.colorStops[0].color};"></span>`;
          res += (marker + item.seriesName+ '：' + item.value + (item.seriesName === '图片总大小' ? 'MB' : '个') + '<br>')
        });
        return res;
      },
      axisPointer: { type: 'shadow' }
    },
    grid: { left: '70', right: '60', bottom: '20%' },
    legend: {
      top: '20',
      itemGap: 30,
      itemWidth: 5,
      itemHeight: 5,
      textStyle: {
        color: '#a4d8fd',
        fontSize: 14,
        padding: [0, 0, 0, 10]
      },
      data: ['图片数量', '图片总大小']
    },
    xAxis: [{
      data: categories,
      type: 'category',
      axisLine: { lineStyle: { color: '#3b69ff' } },
      splitLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        color: '#a4d8fd',
        fontSize: 14,
        rotate: 50
      }
    }],
    yAxis: [
      {
        name: '个',
        nameGap: 15,
        max: maxLeft,
        interval: maxLeft / 5,
        nameTextStyle: { color: '#a4d8fd', fontSize: 14 },
        axisLine: { show: false },
        splitLine: { lineStyle: { type: 'dashed', color: '#063073' } },
        axisTick: { show: false },
        axisLabel: { color: '#a4d8fd', fontSize: 14 }
      },
      {
        name: 'MB',
        nameGap: 15,
        max: maxRight,
        interval: maxRight / 5,
        nameTextStyle: { color: '#a4d8fd', fontSize: 14 },
        axisLine: { show: false },
        splitLine: { lineStyle: { type: 'dashed', color: '#063073' } },
        axisTick: { show: false },
        axisLabel: { color: '#a4d8fd', fontSize: 14 }
      }
    ],
    series: [
      {
        name: '图片数量',
        type: 'bar',
        yAxisIndex: 0,
        itemStyle: { color: '#0bdf51', barBorderRadius: [999, 999, 0, 0] },
        data: colorArray(countData, '#0bdf51'),
        barWidth: 15
      },
      {
        name: '图片总大小',
        type: 'bar',
        yAxisIndex: 1,
        itemStyle: { color: '#10c0fa', barBorderRadius: [999, 999, 0, 0] },
        data: colorArray(sizeData, '#10c0fa'),
        barWidth: 15
      }
    ]
  }
})

</script>

<style scoped></style>
